define(['jquery', 'bootstrap', 'frontend', 'lazyload.min'], function ($, undefined, Frontend, Lazyload) {

    var Controller = {
        index: function () {
            lazyload();
            $(".addon-filter").on("change", ".filter-checkbox input[data-name]", function () {
                var name = $(this).data("name");
                var regexp = new RegExp("[\\?|&]" + name + "=([0-9]+)");
                var url = location.href;
                if ($(this).prop("checked")) {
                    url = url.replace(regexp, '');
                    url = url + (url.indexOf("?") > -1 ? "&" : "?") + name + "=1";
                } else {
                    var searchArr = location.search.substr(1).split("&");
                    searchArr.forEach(function (item, index) {
                        if (item == name + "=1") {
                            delete searchArr.splice(index, 1);
                        }
                    });
                    url = searchArr.length > 0 ? '?' + searchArr.join("&") : '/store.html';
                }
                location.href = url;
            });
            $("body > main > section > div > div.text-line").on("click", function () {
                if ($("#activitylink").length > 0) {
                    location.href = $("#activitylink").attr("href");
                }
            });
            if ($.cookie("faeid") && $(".filterpurchased").length == 0) {
                $(".addon-filter > ul").append('<li class="filter-checkbox filterpurchased"><label><input type="checkbox" data-name="buyable" ' + (Fast.api.query("buyable") == 1 ? 'checked' : '') + '> 过滤已购</label></li>');
            }
        },
        show: function () {
            if (typeof Config.storeshow === 'function') {
                Config.storeshow.call();
            }
            require(['swiper'], function (Swiper) {
                var swiper = new Swiper('.entry-screenshots > .swiper-container', {
                    nextButton: '.swiper-button-next',
                    prevButton: '.swiper-button-prev',
                    autoplay: 2000,
                    height: 450,
                    slidesPerView: 'auto',
                    paginationClickable: true,
                    spaceBetween: 30,
                    freeMode: true
                });

                $(".swiper-container[data-options]").each(function () {
                    new Swiper(this, $(this).data("options"));
                });
            });
            $(document).on("click", ".previewing-tabs,.screenshots-tabs>a", function () {
                $(".previewing-tabs,.screenshots-tabs>a").removeClass("active");
                $(this).addClass("active");
                $(".previewing-container,.screenshots-container").hide();
                var container = $(".previewing-container[data-name='" + $(this).data("name") + "'],.screenshots-container[data-name='" + $(this).data("name") + "']");
                container.show();
                container.find(".swiper-container").data("swiper").update();
            });
            Layer.photos({
                photos: '.entry-screenshots',
                anim: 5
            });
            $(document).on('copy paste', '#features', function (e) {
                e.preventDefault();
                return false;
            });
            var previewWidthFix = function () {
                if ($(".addon-video-preview").length > 0) {
                    $(".addon-video-preview").width($(".entry-screenshots").width());
                }
            };
            $(window).on("resize", function () {
                previewWidthFix();
            });
            previewWidthFix();

            var headerAction = $(".header-action");
            if (headerAction.length > 0 && $(window).width() > 768) {
                var actionOffset = headerAction.offset().top;
                var inNav = false;
                var check_action = function () {
                    if ($(window).scrollTop() >= actionOffset) {
                        if (!inNav) {
                            $("body").addClass("inheadernav");
                            $(".navbar-header").append(headerAction.clone());
                            $(".navbar-header .header-action [data-toggle=popover][data-image]").popover({
                                html: true,
                                trigger: 'hover',
                                content: function () {
                                    var placement = $(this).data("placement");
                                    var attr = ["top", "bottom"].indexOf(placement) > -1 ? 'width="200"' : 'height="200"';
                                    var text = $(this).data("text") || "";
                                    return '<img src="' + $(this).data('image') + '" ' + attr + ' />' + (text ? "<p class='text-center mt-1 mb-0'>" + text + "</p>" : "");
                                }
                            });
                            inNav = true;
                        }
                    } else {
                        $("body").removeClass("inheadernav");
                        $(".navbar-header .header-action").remove();
                        inNav = false;
                    }
                };
                $(window).scroll(function () {
                    check_action();
                });
                check_action();
            }
            if (headerAction.length > 0) {
                $("a[data-toggle='dropdown']", headerAction).on("click", function () {
                    $(this).next("ul").find("li:first-child a.btn-download").trigger("click");
                });
            }

            var lst, ast;
            //应用信息
            $("a.addon-info").popover({
                trigger: 'manual',
                placement: 'bottom',
                title: '',
                html: true,
                content: function () {
                    return Template("infotpl", {})
                },
                animation: false
            }).on("mouseenter", function () {
                var _this = this;
                $(this).popover("show");
                $(this).siblings(".popover").on("mouseleave", function () {
                    $(_this).popover('hide');
                });
            }).on("mouseleave", function () {
                var _this = this;
                ast = setTimeout(function () {
                    if (!$(".popover:hover").length) {
                        $(_this).popover("hide")
                    }
                }, 100);
            });
            //点击立即购买按钮
            if (!isMobile) {
                $(document).on("click", ".header-action a.dropdown-toggle", function () {
                    if ($(this).next().is(".dropdown-menu-price")) {
                        $("li:first-child a", $(this).next()).trigger("click");
                    }
                });
            }

            //切换授权
            $(document).on("click", ".license-item", function () {
                var license = $(this).data("type");
                $(".license-item h4 span.label-info").addClass("hidden");
                $("h4 span.label-info", this).removeClass("hidden");
                $(".btn-buy").data("license", license);
                var price = parseFloat($(this).data("price"));
                if (price <= 0) {
                    $(".btn-buy").html("<i class='fa fa-download'></i> 免费下载");
                } else {
                    $(".btn-buy").html("<i class='fa fa-shopping-cart'></i> 立即购买");
                }
                return false;
            });

            //点击购买
            $(document).on("click", ".btn-buy", function () {
                var that = this;
                var name = $(this).data("name");
                var version = $(this).data("version");
                var license = $(this).data("license");
                var type = $(this).data("type");
                Fast.api.ajax({
                    url: 'store/buy',
                    data: {name: name, version: version, license: license, type: type}
                }, function (data, ret) {
                    Layer.open({
                        type: 1,
                        title: false,
                        closeBtn: 0,
                        area: isMobile ? [$(window).width() + "px", $(window).height() + "px"] : ["500px", "520px"],
                        shadeClose: true,
                        skin: 'recommend-dialog',
                        content: Template("recommendtpl", {url: data.url})
                    });
                    //Layer.alert("插件将会在新弹出的窗口中开始下载，如果你的浏览器阻止了下载，<a href='" + data.url + "'>请点击这里下载</a>");
                    var filename = name + "-" + version + '.zip';
                    var a = document.createElement("a");
                    document.body.appendChild(a);
                    a.style.display = 'none';
                    a.href = data.url;
                    a.download = filename;
                    a.click();
                    window.URL.revokeObjectURL(data.url);
                    return false;
                }, function (data, ret) {
                    if (ret && ret.code === -2) {
                        Fast.api.open(ret.data.payurl, __('立即支付'), {
                            area: isMobile ? [$(window).width() + "px", $(window).height() + "px"] : ["650px", "750px"],
                            shade: 0.6,

                            shadeClose: false,
                            end: function () {
                                Fast.api.ajax({
                                    url: 'store/check',
                                    data: {name: name}
                                }, function (data) {
                                    $("a.btn.btn-download,a.btn.btn-buy").removeClass("btn-buy").addClass("btn-download").html('<i class="fa fa-download"></i> 立即下载');
                                    $(".btn-buy").removeClass("btn-buy").addClass("btn-download");
                                    Layer.alert("购买成功！你稍后还可以在 <b>会员中心</b> -> <b>我购买的插件</b> 中查看！", {
                                        icon: 1, title: "温馨提示", btn: ["立即下载", "暂不下载"], yes: function () {
                                            $(that).trigger("click");
                                        }
                                    });
                                    return false;
                                }, function (data) {
                                    Layer.alert("扫码支付后如果仍然无法立即下载，请不要重复支付，请加<a href='https://jq.qq.com/?_wv=1027&k=54I6mts' target='_blank'>QQ群：675115483</a>向管理员反馈", {title: '温馨提示'});
                                    return false;
                                });
                            }
                        });

                    } else if (ret && ret.msg.indexOf("请登录后再操作") > -1) {
                        //登录提示
                        Fast.api.account(function (data) {
                            $(that).trigger("click");
                        });
                    } else {
                        Layer.alert(ret.msg);
                    }
                    return false;
                });
            });

            //点击购买(下载)
            $(document).on("click", ".btn-download", function () {
                var that = this;
                var name = $(this).data("name");
                var version = $(this).data("version");
                var license = $(this).data("license");
                var type = $(this).data("type");
                Fast.api.ajax({
                    url: 'store/download',
                    data: {name: name, version: version, license: license, type: type}
                }, function (data, ret) {
                    //window.open(data.url);
                    Layer.alert("应用插件将会在新弹出的窗口中开始下载，如果你的浏览器阻止了下载，<a href='" + data.url + "'>请点击这里下载</a>", {title: "温馨提示"});
                    var filename = name + "-" + version + '.zip';
                    var a = document.createElement("a");
                    document.body.appendChild(a);
                    a.style.display = 'none';
                    a.href = data.url;
                    a.download = filename;
                    a.click();
                    window.URL.revokeObjectURL(data.url);
                    return false;
                }, function (data, ret) {
                    if (ret && ret.msg.indexOf("请登录后再操作") > -1) {
                        var value = "; " + document.cookie;
                        var parts = value.split("; username=");
                        var type = parts.length == 2 ? "login" : "register";
                        //登录提示
                        Fast.api.account(function () {
                            $(that).trigger("click");
                        });
                    } else {
                        Layer.alert(ret.msg);
                    }
                    return false;
                });
            });
            //点击升级授权
            $(document).on("click", ".btn-upgrade", function () {
                var name = $(this).data("name");
                Layer.confirm("升级到高级授权需要补差价￥" + $(this).data("money") + "元，是否继续？", {icon: 3}, function () {
                    Fast.api.ajax({
                        url: 'order/upgrade',
                        data: {name: name}
                    }, function (data, ret) {
                        Layer.closeAll();
                        Fast.api.open(data.payurl, "立即支付", {
                            area: isMobile ? [$(window).width() + "px", $(window).height() + "px"] : ["650px", "580px"],
                            shade: 0.3,
                            shadeClose: false,
                            end: function () {
                                location.reload();
                            }
                        });
                        return false;
                    }, function (data, ret) {
                        Layer.alert(ret.msg);
                        return false;
                    });
                });
                return false;
            });

            if (!('ontouchstart' in document.documentElement)) {
                var aside = $("#secondary");
                var preview = $(".panel:first", aside);
                if (aside.length > 0 && preview.height() < $(window).height()) {
                    var demo = $(".panel-demo", aside);
                    var offset = aside.height() + aside.offset().top;
                    var check_aside = function () {
                        if ($(window).scrollTop() + 60 >= offset) {
                            preview.css({"position": "fixed", "top": "60px", width: aside.width() + "px", zIndex: 9});
                            if (demo) {
                                demo.css({
                                    "position": "fixed",
                                    "top": preview.position().top + preview.height() + 15,
                                    width: aside.width() + "px",
                                    zIndex: 9
                                });
                            }
                        } else if (preview.css("position") == "fixed") {
                            preview.removeAttr("style");
                            demo.removeAttr("style");
                        }
                    };
                    $(window).scroll(function () {
                        check_aside();
                    });
                    check_aside();
                }
            } else {
                if ($(".entry-content").height() < 360) {
                    $(".entry-content .read-more").remove();
                }
            }
            $(document).on("click", ".entry-content .read-more a", function () {
                $(".entry-content").css("max-height", 9999);
                $(".entry-content .read-more").fadeOut();
                return false;
            });
            $('body').scrollspy({target: '#navigation'});
            //查看更多
            $(document).on("click", ".read-more-timeline", function () {
                $(".main-timeline .timeline").removeClass("hidden");
                $(this).remove();
            });

            $(".expandall a").on("click", function () {
                $(this).parent().parent().find("dl.hide").fadeIn();
                $(this).fadeOut();
            });

            $(document).on("click", ".btn-viewvideo", function () {
                var title = $(this).data("title") || $(this).attr("title") || "视频介绍";
                var url = $(this).data("url") || $(this).attr("href");
                Layer.open({
                    type: 1,
                    title: title,
                    maxmin: true,
                    area: ['auto', $(window).height() * 0.8 + "px"],
                    shade: .8,
                    content: url,
                    content: '<video style="height:100%;" src="' + url + '" controls autoplay></video>',
                    success: function (layero, index) {
                        $(".layui-layer-content video", layero).css("float", "left").on('loadedmetadata', function () {
                            $(window).trigger("resize");
                        });
                    }
                });
                return false;
            });

            $(document).on("click", "#selectversion", function () {
                Layer.open({
                    title: '选择版本',
                    type: 1,
                    content: Template("versiontpl", {}),
                    btn: false
                });
                return false;
            });
            $(document).on("change", "#versionlist", function () {
                location.href = "?version=" + $(this).val();
                return false;
            });

            if ($.cookie("faeid") && $(".btn-buy").length > 0) {
                var name = $(".btn-buy").data("name");
                Fast.api.ajax({
                    url: 'store/check',
                    loading: false,
                    data: {name: name}
                }, function (data) {
                    if ($(".dropdown-menu-price").length > 0) {
                        $(".dropdown-menu-price").prev().html('<b><i class="fa fa-download"></i> 立即下载</b>').addClass("btn-download").attr("data-name", name);
                        $(".dropdown-menu-price").replaceWith(data);
                    }
                    $("a.btn.btn-download,a.btn.btn-buy,.header-action .btn.dropdown-toggle[data-toggle='dropdown']:has(.fa-shopping-cart)")
                        .removeClass("btn-buy").addClass("btn-download").data("name", name).html('<i class="fa fa-download"></i> 立即下载');
                    $(".btn-buy").removeClass("btn-buy").addClass("btn-download");
                    return false;
                }, function () {
                    return false;
                });
            }
            require(['watermark'], function (Watermark) {
                Watermark.init({"watermark_parent_node":"features", "watermark_txt": $.cookie('faeid') + new Date().getTime(), "watermark_width": 300, "watermark_height": 100, "watermark_alpha": 0.005, "watermark_font": "Arial", "watermark_fontsize": "12px"});
            });
            require(['comment']);
        },
        post: function () {
            var formEdited = false;
            $(window).bind('beforeunload', function () {
                if (formEdited) {
                    return '您输入的内容尚未保存，确定离开此页面吗？';
                }
            });
            require(['form', 'bigfileuploader'], function (Form, Uploader) {
                $(document).on("change", ".uploadvideo", function () {
                    (new Uploader(this, {
                        url: 'https://video.fastadmin.net/upload.php',
                        maxFileSize: 200,
                        error: function (o) {
                            Toastr.error(o.message);
                        },
                        success: function (o) {
                            $("#c-videourl").val(o.url);
                            $("#c-videoimage").val(o.image).trigger("change");
                            Toastr.success(o.message);
                            $(".btn-uploadvideo").removeClass("btn-primary").addClass("btn-success").prop("disabled", false).find("em").text("上传成功");
                            $(".btn-uploadvideo").find("i").removeClass("fa-upload").addClass("fa-check");
                            $.post("/video/thumb", $.extend({}, Config.params, {image: o.image}));
                        },
                        progress: function (o) {
                            $(".btn-uploadvideo").prop("disabled", true).find("em").text("已上传 " + o.percent.toFixed(2) + " %");
                        },
                        params: Config.params
                    })).start();
                });
                Layer.open({
                    type: 1,
                    title: Fast.api.query("name") ? "修改插件" : "发布插件",
                    content: Template("posttpl", {}),
                    btn: null,
                    maxmin: true,
                    moveOut: true,
                    zIndex: 1999,
                    area: isMobile ? [$(window).width() + "px", $(window).height() + "px"] : ["800px", "500px"],
                    offset: "b",
                    success: function (layero, index) {
                        Form.api.bindevent($("#post-form", layero), function (data, ret) {
                            Layer.close(index);
                            Layer.alert(ret.msg, function () {
                                $(window).unbind('beforeunload');
                                location.href = ret.url;
                            });
                            return false;
                        });
                        if (Fast.api.query("name")) {
                            $("#post-form #c-title").trigger("change");
                            $("#c-price").trigger("change");
                        }
                    },
                    min: function (layero) {
                        $(".layer-footer", layero).hide();
                    },
                    restore: function (layero) {
                        $(".layer-footer", layero).show();
                    },
                    cancel: function (index, layero) {
                        if (formEdited) {
                            Layer.confirm("当前内容还未保存，关闭将丢失已录入的内容，确认关闭？", function () {
                                $(window).unbind('beforeunload');
                                history.go(-1);
                            });
                            return false;
                        } else {
                            history.go(-1);
                        }
                    }

                });
            });
            $(document).on("keyup change", "#c-price", function () {
                $("[data-license='extended']").toggleClass("hidden", parseFloat($(this).val()) <= 0);
            });
            $(document).on("keyup change", "#post-form input,#post-form textarea,#post-form select", function (e) {
                if (e.type === 'keyup') {
                    formEdited = true;
                }
                var obj = $("[data-ref='" + $(this).prop("id") + "']");
                if (obj.length > 0) {
                    if ($(this).is("textarea")) {
                        obj.html(marked($(this).val()));
                    } else {
                        obj.html($(this).val());
                    }
                }
            });
        },
        app: function () {
            require(['swiper'], function (Swiper) {
                var swiper = new Swiper('.entry-screenshots > .swiper-container', {
                    nextButton: '.swiper-button-next',
                    prevButton: '.swiper-button-prev',
                    autoplay: 2000,
                    height: 450,
                    slidesPerView: 'auto',
                    paginationClickable: true,
                    spaceBetween: 30,
                    freeMode: false
                });
                $(".swiper-container[data-options]").each(function () {
                    new Swiper(this, $(this).data("options"));
                });
            });
            Layer.photos({
                photos: '.entry-screenshots',
                anim: 5,
                scrollbar: true
            });
        }
    };

    return Controller;
});
